/*******************************************************************************
* CSCI321 Major Project 2010 - University of Wollongong                        *
********************************************************************************
* Program:		WeaveEdit                                              *
* Authors:		Simon Allen (Student#: 3457527, Unix: sa655)           *
*			Scott Bellis (Student#: 3479110, Unix: sjb900)         *
*			Jason Benger (Student#: 3454137, Unix: jb960)          *
*			Timothy Newmarch (Student#: 3459263 Unix: tgn336)      *
*			Benjamin Richardson (Student# 3467752, Unix: bjr401)   *
* Supervisor:		Daniel F. Saffioti                                     *
* Modified:		28/10/2010                                             *
* Description:		WeaveEdit is a highly portable collaborative text      *
*			editor and word processor, allowing several users to   *
*			read and edit multiple documents at the same time.     *
*			It is available for Mac OS X, Windows and Linux,       *
*			utilising Nokia's Qt development framework.            *
*******************************************************************************/


#include "fortranindenter.h"
#include "Editor/texteditor.h"


/**
  * Indent a line using custom automatic indentation rules defined below.
  */
void FortranIndenter::indent()
{
	QTextCursor cursor = editor->textCursor();
	QString trimmedPrevLine;
	int numTabs = 0, newLinePos = cursor.position() - 2;

	// Go back till we find the first non-space character.
	while (newLinePos >= 0 && editor->document()->characterAt(newLinePos).isSpace())
		newLinePos--;

	// Document has no non-space characters in it.
	if (newLinePos < 0)
		return;

	cursor.setPosition(newLinePos);
	cursor.select(QTextCursor::LineUnderCursor);

	int start = cursor.selectionStart();

	// Measure current indentation.
	while (start < cursor.selectionEnd() && editor->document()->characterAt(start) == '\t')
	{
		numTabs++;
		start++;
	}

	trimmedPrevLine = cursor.selectedText().trimmed();
	trimmedPrevLine = trimmedPrevLine.toLower();

	// We have a new level of indentation.
	if (trimmedPrevLine.startsWith("do ") || trimmedPrevLine.startsWith("while ")
	    || trimmedPrevLine.startsWith("while(") || trimmedPrevLine.startsWith("if ")
	    || trimmedPrevLine.startsWith("if(") || trimmedPrevLine.startsWith("subroutine ")
	    || trimmedPrevLine.startsWith("function"))
		numTabs++;

	editor->insertPlainText(QString(numTabs, '\t'));
}
